import java.util.HashMap;

public class BuildTree2 {

    int[] postorder;
    HashMap<Integer, Integer> map;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.postorder = postorder;
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return process(0, inorder.length - 1, 0, postorder.length - 1);
    }

    public TreeNode process(int inL, int inR, int postL, int postR) {
        if (inL > inR || postL > postR) return null;
        int index = map.get(postorder[postR]);
        TreeNode node = new TreeNode(postorder[postR]);
        node.left = process(inL, index - 1, postL, postL + index - 1 - inL);
        node.right = process(index + 1, inR, postL + index - inL, postR - 1);
        return node;
    }
}
